import Taro, {Component} from '@tarojs/taro'
import { View } from '@tarojs/components'
import { calcSurplusTime } from '@/utils/utils'
import classNames from 'classnames'

interface IProps {
  seconds: number
  onTimeUp?: any
  className?:string
}


/**
 * 格式化时间
 * @param num
 */
const formatNum = num => (num <= 9 ? `0${num}` : `${num}`)

export default class index extends Component<IProps, {}> {
  state: any
  timer: any
  seconds: any

  static options = {
    addGlobalClass: true
  }

  constructor() {
    super(...arguments)
    this.timer = undefined
    this.seconds = 0
    const { minutes, seconds } = calcSurplusTime()
    this.state = {
      minutes,
      seconds
    }
  }

  componentDidHide() {
    this.clearTimer()
  }

  componentWillUnmount() {
    this.clearTimer()
  }

  componentWillReceiveProps(nextProps) {
    if (JSON.stringify(this.props) === JSON.stringify(nextProps)) {
      return false
    }
    console.log('-------------------------------- nextProps --------------------------------')
    this.seconds = nextProps.seconds
    this.clearTimer()
    this.setTimer()
  }

  /**
   * 开启倒计时
   */
  setTimer() {
    if (!this.timer) this.countdown()
  }

  /**
   * 清除计时器
   */
  clearTimer() {
    if (this.timer) {
      clearTimeout(this.timer as number)
      this.timer = undefined
    }
  }

  /**
   * 倒计时
   */
  countdown() {
    const { minutes, seconds } = calcSurplusTime(this.seconds)

    this.setState({
      minutes,
      seconds
    })
    this.seconds--

    if (this.seconds < 0) {
      this.clearTimer()
      this.props.onTimeUp && this.props.onTimeUp()
      return
    }

    this.timer = setTimeout(() => {
      this.countdown()
    }, 1000)
  }


  render() {
    const { className } = this.props
    const { minutes, seconds } = this.state
    return (<View className={classNames('order-count-down', className)}>{formatNum(minutes)}:{formatNum(seconds)}</View>)
  }
}
